package com.scu.hotelsystem.service;

import com.scu.hotelsystem.dao.StaffDao;
import com.scu.hotelsystem.pojo.Staff;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.SQLIntegrityConstraintViolationException;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class StaffServiceImpl implements StaffService {

    @Autowired
    private StaffDao staffDao;

    @Override
    public int verifyLogin(String account, String password) {
        int id;
        Staff staff;

        if (account.length() == 11){
            staff = staffDao.selectValidStaffByPhonePass(account, password);
        }else{
            try{ id = Integer.parseInt(account); }
            catch (NumberFormatException e){return FAILED;}
            staff = staffDao.selectValidStaffByIdPass(id, password);
        }

        return staff == null? FAILED : staff.getId();
    }

    @Override
    public List<Staff> getStaffList(int index, int limit) {
        return staffDao.searchValidStaff(new Staff(), index, limit);
    }

    @Override
    public List<Staff> searchStaffList(Staff staff, int index, int limit) {
        List<Staff> staffList;
        staffList = staffDao.searchValidStaff(staff, index, limit);
        return staffList;
    }

    @Override
    public int updateStaff(Staff staff) throws SQLIntegrityConstraintViolationException{
        int n = 0;
        try{
            n = staffDao.updateStaff(staff);
        }catch (DataAccessException e){
            throw new SQLIntegrityConstraintViolationException("手机或身份证号已被使用");
        }

        return n;
    }

    @Override
    public int addStaff(Staff staff) throws SQLIntegrityConstraintViolationException {
        int n = 0;
        List<Staff> staffList;

        staffList = staffDao.selectValidStaffByPhoneOrResdId(staff.getPhone(), staff.getResdId());
        if (staffList.size()!=0){
            throw new SQLIntegrityConstraintViolationException("手机或身份证号已被使用");
        }

        try{
            staff.setAddTime(new Date());
            n = staffDao.insertAndUpdateStaff(staff);
        }catch (DataAccessException e){
            throw new SQLIntegrityConstraintViolationException("身份证号和手机号已被分别绑定");
        }

        return n;
    }

    @Override
    public int deleteStaff(int[] idList) throws IllegalArgumentException{
        int n = 0;

        try{
            n = staffDao.setStaffsInvalidById(idList);
        }catch (DataAccessException e){
            throw new IllegalArgumentException("传入数组不能为空");
        }

        return n;
    }


}
